package com.study.a12FinnalTest;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Server {
    // 线程安全的集合，存储所有登录成功客户端的输出流
    private static List<PrintWriter> clientWriters = new CopyOnWriteArrayList<>();
    public static void main(String[] args) throws IOException {

        //将用户姓名和密码从文件中读取出来
        List<String> nameList = new ArrayList<>();
        List<String> passwordList = new ArrayList<>();

        FileReader fr = new FileReader("E:\\java-code\\idea-code-study\\mysocketnet\\User\\userandpassword.txt");
        BufferedReader br1 = new BufferedReader(fr);
        String line;
        while ((line = br1.readLine()) != null) {
            // 跳过空行
            if (line.trim().isEmpty()) {
                continue;
            }
            // 分割行内容
            String[] userInfo = line.split("&&");
            // 校验格式：确保分割后有2个元素（用户名和密码）
            if (userInfo.length != 2) {
                System.err.println("跳过格式错误的行：" + line);
                continue;
            }
            // 提取用户名和密码（去除前后空格，避免空白字符干扰）
            String userName = userInfo[0].trim();
            String userPassword = userInfo[1].trim();
            // 添加到列表
            nameList.add(userName);
            passwordList.add(userPassword);
        }
        System.out.println("用户列表：" + nameList);
        System.out.println("密码列表：" + passwordList);





        ServerSocket serverSocket = new ServerSocket(9000);
        System.out.println("服务器启动，等待客户端连接...");

// 1. 外层循环：持续接受新客户端连接
        while (true) {
            Socket socket = serverSocket.accept(); // 接受客户端连接
            System.out.println("新客户端连接：" + socket);

            // 2. 为每个客户端创建独立线程处理，避免阻塞主线程
            new Thread(() -> {
                PrintWriter pw=null;
                try (
                        // 3. 一次性创建流对象（try-with-resources自动关闭）
                        InputStreamReader isr = new InputStreamReader(socket.getInputStream());
                        BufferedReader br = new BufferedReader(isr);
                        OutputStream os = socket.getOutputStream();
                        PrintWriter tempPw = new PrintWriter(os, true) // 自动刷新
                ) {
                    pw=tempPw;
                    int count = 0;
                    String name = null;
                    String password = null;
                    boolean loginSuccess = false;

                   String choice = br.readLine();

                   if(choice.equals("1")) {
                       // 登录流程
                       while (count < 2) {
                           if (count == 0) {
                               name = br.readLine();
                               count++;
                           } else if (count == 1) {
                               password = br.readLine();

                               // 验证用户名密码
                               for (int i = 0; i < nameList.size(); i++) {
                                   if (nameList.get(i).equals(name) && passwordList.get(i).equals(password)) {
                                       /*pw.println("登录成功，开始聊天");*/ // 使用PrintWriter简化发送
                                       loginSuccess = true;
                                       clientWriters.add(pw);
                                       System.out.println(name + " 登录成功，当前在线人数：" + clientWriters.size());
                                       break;
                                   }

                               }

                               if (!loginSuccess) {
                                   pw.println("不存在该用户或密码错误");
                                   socket.close(); // 登录失败，关闭连接
                                   return; // 退出线程
                               }
                               count++; // 登录成功，进入消息循环
                           }
                       }
                   }else if(choice.equals("2")){
                       System.out.println("正在注册");
                       //注册流程
                       while (count < 2) {
                           if (count == 0) {
                               name = br.readLine();
                               count++;
                           } else if (count == 1) {
                               password = br.readLine();

                               // 检查用户名是否已存在
                               if (nameList.contains(name)) {
                                   pw.println("用户名已存在，请重新输入");
                                   count=0;
                                   continue; // 重新输入用户名
                               }else {
                                   // 注册成功，添加到列表
                                   pw.println("注册成功");
                                   nameList.add(name);
                                   passwordList.add(password);
                                   //添加到userandpassword.txt文件
                                   try (FileWriter fw = new FileWriter("userandpassword.txt", true)) {
                                       fw.write(name + "&&" + password + "\n");
                                   } catch (IOException e) {
                                       System.err.println("写入文件时出错：" + e.getMessage());
                                   }
                               }
                               // 验证用户名密码

                                       loginSuccess = true;
                                       clientWriters.add(pw);
                                       System.out.println(name + " 登录成功，当前在线人数：" + clientWriters.size());
                                       break;


                               }


                               count++; // 登录成功，进入消息循环
                           }


                   }

                    // 4. 登录成功后：持续接收客户端消息并回复
                    // ... 登录成功后的消息循环 ...
                    String clientMsg;
                    while ((clientMsg = br.readLine()) != null) {
                        if (clientMsg.equals("exit")) {
                            break;
                        }
                        System.out.println(name+"：" + clientMsg);
                        // 构建广播消息（包含发送者用户名）
                        String broadcastMsg = "[" + name + "]: " + clientMsg;
                        // 遍历所有客户端输出流，发送消息
                        for (int i=1;i<clientWriters.size();i++) {
                            PrintWriter writer = clientWriters.get(i);
                            pw.println(broadcastMsg);
                        }
                    }


                } catch (IOException e) {
                    System.out.println("客户端断开连接：" + e.getMessage());
                } finally {
                    if (pw != null) {
                        clientWriters.remove(pw);
                        System.out.println("客户端退出，当前在线人数：" + clientWriters.size());
                    }
                    try {
                        socket.close(); // 确保连接关闭
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start(); // 启动客户端处理线程
        }


    }


}




